package io.framework.modules.sys.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.framework.common.annotation.LogOperation;
import io.framework.common.constant.Constant;
import io.framework.common.exception.ErrorCode;
import io.framework.common.page.PageData;
import io.framework.common.utils.ConvertUtils;
import io.framework.common.utils.DateUtils;
import io.framework.common.utils.ExcelUtils;
import io.framework.common.utils.Result;
import io.framework.common.validator.AssertUtils;
import io.framework.common.validator.ValidatorUtils;
import io.framework.common.validator.group.AddGroup;
import io.framework.common.validator.group.DefaultGroup;
import io.framework.common.validator.group.UpdateGroup;
import io.framework.modules.air.dto.AirCheckExplainDTO;
import io.framework.modules.air.dto.AirDTO;
import io.framework.modules.air.dto.AirDayNumberDTO;
import io.framework.modules.air.dto.AirNdChangeDTO;
import io.framework.modules.air.entity.AirCheckExplainEntity;
import io.framework.modules.air.entity.AirDayNumberEntity;
import io.framework.modules.air.entity.AirEntity;
import io.framework.modules.air.entity.AirNdChangeEntity;
import io.framework.modules.air.utils.AirFileCommonUtil;
import io.framework.modules.security.entity.SysUserTokenEntity;
import io.framework.modules.security.service.SysUserTokenService;
import io.framework.modules.security.user.SecurityUser;
import io.framework.modules.security.user.UserDetail;
import io.framework.modules.station.dto.StationDTO;
import io.framework.modules.sys.dto.PasswordDTO;
import io.framework.modules.sys.dto.SysUserDTO;
import io.framework.modules.sys.entity.SysUserEntity;
import io.framework.modules.sys.excel.SysUserExcel;
import io.framework.modules.security.password.PasswordUtils;
import io.framework.modules.sys.service.SysRoleUserService;
import io.framework.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 用户管理
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户管理")
public class SysUserController {
    @Value("${file.upload.path}")
    private String FILE_UPLOAD_PATH;

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleUserService sysRoleUserService;
    /**
     * token
     */
    @Autowired
    private SysUserTokenService sysUserTokenService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "gender", value = "性别", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "deptId", value = "部门ID", paramType = "query", dataType = "String")
    })
    @RequiresPermissions("sys:user:page")
    public Result<PageData<SysUserDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysUserDTO> page = sysUserService.page(params);

        return new Result<PageData<SysUserDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<SysUserDTO> get(@PathVariable("id") Long id) {
        SysUserDTO data = sysUserService.get(id);

        //用户角色列表
        List<Long> roleIdList = sysRoleUserService.getRoleIdList(id);
        data.setRoleIdList(roleIdList);

        return new Result<SysUserDTO>().ok(data);
    }

    @GetMapping("info")
    @ApiOperation("登录用户信息")
    public Result<SysUserDTO> info(HttpServletRequest request) {
        String token = request.getHeader(Constant.TOKEN_HEADER);
        if (StringUtils.isEmpty(token)) {
            return new Result<SysUserDTO>().error(ErrorCode.TOKEN_INVALID);
        }
        SysUserTokenEntity tokenEntity = sysUserTokenService.getByToken(token);

        SysUserDTO user = sysUserService.get(tokenEntity.getUserId());

        SysUserDTO data = ConvertUtils.sourceToTarget(user, SysUserDTO.class);
        return new Result<SysUserDTO>().ok(data);
    }

    @PutMapping("password")
    @ApiOperation("修改密码")
    @LogOperation("修改密码")
    public Result password(PasswordDTO dto, HttpServletRequest request) {
        //效验数据
        ValidatorUtils.validateEntity(dto);
        String token = request.getHeader(Constant.TOKEN_HEADER);
        if (StringUtils.isEmpty(token)) {
            return new Result().error(ErrorCode.TOKEN_INVALID);
        }
        SysUserTokenEntity tokenEntity = sysUserTokenService.getByToken(token);

        SysUserDTO user = sysUserService.get(tokenEntity.getUserId());

        //原密码不正确
        if (!PasswordUtils.matches(dto.getPassword(), user.getPassword())) {
            return new Result().error(ErrorCode.PASSWORD_ERROR);
        }
        sysUserService.updatePassword(user.getId(), dto.getNewPassword());
        return new Result();
    }


    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "path", dataType = "Long")
    @ApiOperation("重置密码")
    @LogOperation("重置密码")
    public Result resetpassword(String userId) {
        //效验数据
//        ValidatorUtils.validateEntity(dto);
//        String token = request.getHeader(Constant.TOKEN_HEADER);
//        if (StringUtils.isEmpty(token)) {
//            return new Result().error(ErrorCode.TOKEN_INVALID);
//        }
//        SysUserTokenEntity tokenEntity = sysUserTokenService.getByToken(token);
//        PasswordDTO dto = new PasswordDTO();
//        SysUserDTO user = sysUserService.get(id);
//
//        //原密码不正确
//        if (!PasswordUtils.matches(dto.getPassword(), user.getPassword())) {
//            return new Result().error(ErrorCode.PASSWORD_ERROR);
//        }

        SysUserDTO user = sysUserService.get(Long.valueOf(userId));

//        Syhb@wwq888
        String newPassword = "Syhb@";
        if(user != null){
            newPassword = newPassword+user.getUsername()+"888";
        }

        sysUserService.updatePassword(Long.valueOf(userId), newPassword);
        return new Result();
    }



    @PostMapping
    @ApiOperation("保存")
    @LogOperation("添加用户信息")
    @RequiresPermissions("sys:user:save")
    public Result save(SysUserDTO dto) {

        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        SysUserDTO user = sysUserService.getByUsername(dto.getUsername());
        if (user != null) {
            return new Result().error(ErrorCode.USERNAME_ALREADY_USERD);
        }
        sysUserService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改用户信息")
    @RequiresPermissions("sys:user:update")
    public Result update(SysUserDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        SysUserDTO user = sysUserService.getByUsername(dto.getUsername());
        if (user != null && !dto.getId().equals(user.getId())) {
            return new Result().error(ErrorCode.USERNAME_ALREADY_USERD);
        }

        dto.setUpdateDate(new Date());
        sysUserService.update(dto);

        return new Result();
    }

    @DeleteMapping("{id}")
    @ApiOperation("删除")
    @LogOperation("删除用户信息")
    @RequiresPermissions("sys:user:delete")
    public Result delete(@PathVariable("id") Long id) {

        sysUserService.deleteById(id);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("批量删除")
    @LogOperation("批量删除用户信息")
    @RequiresPermissions("sys:user:deleteBatchete")
    public Result deleteBatch(Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        sysUserService.deleteBatchIds(Arrays.asList(ids));

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    //@RequiresPermissions("sys:user:export")
    @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "String")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SysUserDTO> list = sysUserService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, SysUserExcel.class);
    }

    @PostMapping("uploadFile")
    @ApiOperation("用户信息上传")
    @ApiImplicitParam(name = "multipartFile", value = "文件", paramType = "query", dataType = "String", required = true)
    @LogOperation("用户信息上传")
    //@RequiresPermissions("sys:user:upload")
    public Result uploadFile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(filename)){
            return new Result().error(ErrorCode.UPLOAD_FILE_EMPTY);
        }
        File file1 = new File(FILE_UPLOAD_PATH + DateUtil.format(new Date(), "yyyy-MM-dd"));
        if (!file1.exists()) {
            file1.mkdirs();
        }
        File excelFile = new File(file1, File.separator + DateUtil.format(new Date(), "HHmmss") + filename.substring(filename.indexOf(".")));
        try {
            file.transferTo(excelFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filePath = excelFile.getPath();

        List<SysUserDTO> airDTOList = new ArrayList<>();
        List<SysUserDTO> cityStationList = sysUserService.readuser(filePath);
        if(CollectionUtils.isNotEmpty(cityStationList)){
            airDTOList.addAll(cityStationList);
        }
        sysUserService.insertBatch(ConvertUtils.sourceToTarget(airDTOList, SysUserEntity.class));

        return new Result().ok("上传成功");
    }





}